package com.workstudy.controller;

import com.workstudy.domain.Loginlog;
import com.workstudy.domain.User;
import com.workstudy.service.LoginlogService;
import com.workstudy.service.UserService;
import com.workstudy.support.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import zhibi.common.support.exception.TipException;
import zhibi.common.util.ip.IPUtil;
import zhibi.common.util.security.SecurityUtil;

import java.util.Date;


@RequestMapping
@Controller
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private LoginlogService loginlogService;

    /**
     * 登录后的首页
     *
     * @return
     */
    @RequestMapping({"", "index"})
    public String index(Model model) {
        return "index";
    }


    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(String username, String password) {
        User user = new User();
        user.setNo(username);
        user.setPassword(SecurityUtil.MD5(password, PASSWORD_COUNT).toLowerCase());
        user = userService.selectOne(user);
        if (null == user) {
            throw new TipException("用户名或者密码错误", "/login");
        }
        String ip = IPUtil.getRemortIP(request);
        if (!ip.equalsIgnoreCase(user.getIp()) && user.getType().equalsIgnoreCase("student")) {
            throw new TipException("用户只能在指定的ip登录", "/login");
        }
        /**
         * 保存登录信息
         */
        Loginlog loginlog = new Loginlog();
        loginlog.setAddtime(new Date());
        loginlog.setIp(ip);
        loginlog.setUserId(user.getId());
        loginlogService.insertSelective(loginlog);

        session.setAttribute(SESSION_USER, user);
        logger.info("{} - 登录成功", username);
        return redirect("/");
    }

    @RequestMapping("logout")
    public String logout() {
        session.removeAttribute(SESSION_USER);
        return "login";
    }
}
